package com.meritdata.cloud.data.service.application.service.impl;

import com.meritdata.cloud.data.base.Page;
import com.meritdata.cloud.data.service.application.dao.IApplicationDao;
import com.meritdata.cloud.data.service.application.model.Application;
import com.meritdata.cloud.data.service.application.service.IApplicationService;
import com.meritdata.cloud.data.util.Base64Util;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class ApplicationService implements IApplicationService {

    private static final String LOAD_HQL = " select new Application(id, key, secret, credentialName,  name," +
            "duration,  durationUnit,  desc,  createTime," +
            "updateTime,  creator,  reviserId,  apiLimit) from Application";

    @Autowired
    private IApplicationDao dao;

    @Override
    public void add(Application app) {
        dao.save(app);
    }

    @Override
    public List<Application> all() {
        return dao.findAll();
    }

    @Override
    public boolean save(Application application) {
        Date now = new Date();
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        application.setCreateTime(now);
        application.setCreator("sukui");
        application.setKey(key);
        try {
            application.setSecret(Base64Util.encode(key));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        application.setReviserId("sukui");
        application.setUpdateTime(now);
        dao.save(application);
        return true;
    }

    @Override
    public Application get(Long id) {
        return dao.findOne(id);
    }

    @Override
    public Application load(Long id) {
        List<Application> apps =  dao.findHql(LOAD_HQL + " where id = :id", id);
        return (null == apps || apps.size() == 0) ? null : apps.get(0);
    }

    @Override
    public boolean delete(Long id) {
        return dao.delete(id) > 0;
    }

    @Override
    public boolean udpate(Application application) {
        application.setUpdateTime(new Date());
        dao.update(application);
        return true;
    }

    @Override
    public Page page(Page page) {
        return dao.pageHql(LOAD_HQL, page.getPageNum(), page.getPageSize(), null);
    }

}
